package com.code.gen.util;

import java.util.Arrays;
import java.util.List;

import com.code.gen.bean.bo.CodeGenPropertiesSystem;
import com.code.gen.bean.bo.database.CodeGenField;
import com.code.gen.bean.bo.database.CodeGenTable;
import com.code.gen.constant.CodeGenConstant;
import com.code.gen.enums.ECodeGenFieldEquals;
import com.code.gen.enums.ECodeGenHtmlType;
import com.code.gen.enums.ECodeGenQueryType;
import com.code.gen.enums.ECodeGenType;
import com.sojson.enums.core.EGeneralYesNo;
import com.sojson.util.StringUtil;

/**
 * 代码生成器 工具类
 *
 * @author lyh
 */
public class CodeGenUtil {

    private static final CodeGenPropertiesSystem system = new CodeGenPropertiesSystem();

    /**
     * 初始化表信息
     */
    public static void initTable(CodeGenTable table) {
        String databaseTablePrefix = system.getDatabaseTablePrefix();
        if (system.isDatabasePrefix() && StringUtil.isNotBlank(databaseTablePrefix)) {
            table.setClassName(CodeGenPropertiesUtil.toUpperCase(CodeGenPropertiesUtil
                .enableFieldMapUnderscoreToCamelCase(tableRemovePrefix(table.getTableName()).toLowerCase())));
        } else {
            table.setClassName(CodeGenPropertiesUtil.toUpperCase(
                CodeGenPropertiesUtil.enableFieldMapUnderscoreToCamelCase(table.getTableName().toLowerCase())));
        }
        table.setPackageName(system.getBasePath());
        table.setModuleName(system.getModuleName());
        table.setBusinessName(system.getBusinessName());
        table.setFunctionName(table.getTableComment());
        table.setFunctionAuthor(system.getAuthor());
        table.setGenType(ECodeGenType.THIS.getCode());
        table.setGenPath("");
        table.setParentMenuId(system.getParentMenuId());
        table.setOptions("{}");
    }

    /**
     * 去除表的前缀
     */
    public static String tableRemovePrefix(String tableName) {
        if (!"".equals(system.getDatabaseTablePrefix().trim())) {
            if (tableName.startsWith(system.getDatabaseTablePrefix())) {
                tableName = tableName.substring(
                    tableName.indexOf(system.getDatabaseTablePrefix()) + system.getDatabaseTablePrefix().length(),
                    tableName.length());
            }
        }
        return tableName;
    }

    /**
    * 初始化列属性字段
    */
    public static void initColumnField(CodeGenField column, CodeGenTable table) {
        String columnType = column.getColumnType();
        String dataType = getDbType(columnType);
        String columnName = column.getColumnName();
        // 设置字段类型
        column.setColumnType(dataType);
        // 设置java字段名
        column.setJavaField(CodeGenPropertiesUtil.enableFieldMapUnderscoreToCamelCase(columnName.toLowerCase()));
        for (ECodeGenFieldEquals fieldEquals : ECodeGenFieldEquals.values()) {
            if (null != fieldEquals.getDatabase()) {
                if (fieldEquals.getDatabase().equalsIgnoreCase(dataType)) {
                    column.setJavaType(fieldEquals.getJava());
                    break;
                }
            }
        }

        if (arraysContains(CodeGenConstant.COLUMNTYPE_STR, dataType)) {
            // 字符串长度超过500设置为文本域
            Integer columnLength = getColumnLength(columnType);
            String htmlType =
                columnLength >= 500 ? ECodeGenHtmlType.TEXTAREA.getCode() : ECodeGenHtmlType.INPUT.getCode();
            column.setHtmlType(htmlType);
        } else if (arraysContains(CodeGenConstant.COLUMNTYPE_TIME, dataType)) {
            column.setJavaType(ECodeGenFieldEquals.DATE.getJava());
            column.setHtmlType(ECodeGenHtmlType.DATETIME.getCode());
        } else if (arraysContains(CodeGenConstant.COLUMNTYPE_NUMBER, dataType)) {
            column.setHtmlType(ECodeGenHtmlType.INPUT.getCode());

            // 如果是浮点型 统一用BigDecimal
            String[] str = StringUtil.split(StringUtil.substringBetween(columnType, "(", ")"), ",");
            if (str != null && str.length == 2) {
                column.setJavaType(ECodeGenFieldEquals.DECIMAL.getJava());
            }
            // 如果是整形
            else if (str != null && str.length == 1 && Integer.parseInt(str[0]) <= 10) {
                column.setJavaType(ECodeGenFieldEquals.INT.getJava());
            }
            // 长整形
            else {
                column.setJavaType(ECodeGenFieldEquals.BIGINT.getJava());
            }
        }

        int yes = EGeneralYesNo.YES.getCode();
        int no = EGeneralYesNo.NO.getCode();
        Integer isPk = column.getIsPk();

        if (system.getViewNoAddEdit().contains(column.getJavaField()) || isPk == yes) {
            // 插入字段
            column.setIsAdd(no);
            // 编辑字段
            column.setIsEdit(no);
            // 是否必填
            column.setIsRequired(no);
        } else {
            // 插入字段
            column.setIsAdd(yes);
            // 编辑字段
            column.setIsEdit(yes);
            // 是否必填
            column.setIsRequired(yes);
        }
        // 列表字段
        List<String> resultFields = system.getResultFields();
        List<String> resultNoFields = system.getResultNoFields();
        if (system.getViewNoList().contains(column.getJavaField()) || isPk == yes) {
            column.setIsList(no);
        } else if (resultFields.size() > 0) {
            if (resultFields.contains(column.getColumnName())) {
                column.setIsList(yes);
            } else {
                column.setIsList(no);
            }
        } else if (resultNoFields.size() > 0) {
            if (resultFields.contains(column.getColumnName())) {
                column.setIsList(no);
            } else {
                column.setIsList(yes);
            }
        } else {
            column.setIsList(yes);
        }
        // 查询字段
        List<String> queryFields = system.getQueryFields();
        List<String> queryNoFields = system.getQueryNoFields();
        if (system.getViewNoQuery().contains(column.getJavaField()) || isPk == yes) {
            column.setIsQuery(no);
        } else if (queryFields.size() > 0) {
            if (queryFields.contains(column.getColumnName())) {
                column.setIsQuery(yes);
            } else {
                column.setIsQuery(no);
            }
        } else if (queryNoFields.size() > 0) {
            if (queryNoFields.contains(column.getColumnName())) {
                column.setIsQuery(no);
            } else {
                column.setIsQuery(yes);
            }
        } else {
            column.setIsQuery(yes);
        }
        // 查询字段类型
        if (StringUtil.endsWithIgnoreCase(columnName, "name")) {
            column.setQueryType(ECodeGenQueryType.LIKE.getCode());
        } else {
            column.setQueryType(ECodeGenQueryType.EQ.getCode());
        }
        // 状态字段设置单选框
        if (StringUtil.endsWithIgnoreCase(columnName, "status")) {
            column.setHtmlType(ECodeGenHtmlType.RADIO.getCode());
        }
        // 类型&性别字段设置下拉框
        else if (StringUtil.endsWithIgnoreCase(columnName, "type")
            || StringUtil.endsWithIgnoreCase(columnName, "sex")) {
            column.setHtmlType(ECodeGenHtmlType.SELECT.getCode());
        }
        // 创建时间字段设置时间控件
        else if (StringUtil.endsWithIgnoreCase(
            CodeGenPropertiesUtil.enableFieldMapUnderscoreToCamelCase(column.getColumnName().toLowerCase()),
            system.getCreateTime())) {
            column.setHtmlType(ECodeGenHtmlType.DATETIME.getCode());
        }
        // 文件字段设置上传控件
        else if (StringUtil.endsWithIgnoreCase(columnName, "image")) {
            column.setHtmlType(ECodeGenHtmlType.UPLOAD_IMAGE.getCode());
        }
        // 内容字段设置富文本控件
        else if (StringUtil.endsWithIgnoreCase(columnName, "content")) {
            column.setHtmlType(ECodeGenHtmlType.EDITOR.getCode());
        }
        // 其他字段设置文本框
        else {
            column.setHtmlType(ECodeGenHtmlType.INPUT.getCode());
        }
        if ((ECodeGenHtmlType.DATETIME.getCode().equals(column.getHtmlType()) && !system.getCreateTime()
            .equals(CodeGenPropertiesUtil.toLowerCase(
                CodeGenPropertiesUtil.enableFieldMapUnderscoreToCamelCase(column.getColumnName().toLowerCase()))))
            || ECodeGenHtmlType.CHECKBOX.getCode().equals(column.getHtmlType())
            || ECodeGenHtmlType.UPLOAD_IMAGE.getCode().equals(column.getHtmlType())
            || ECodeGenHtmlType.EDITOR.getCode().equals(column.getHtmlType())) {
            column.setIsQuery(no);
            column.setIsList(no);
        }
    }

    /**
     * 校验数组是否包含指定值
     * 
     * @param arr           数组
     * @param targetValue   值
     * @return
     */
    public static boolean arraysContains(String[] arr, String targetValue) {
        return Arrays.asList(arr).contains(targetValue);
    }

    /**
     * 获取数据库类型字段
     * 
     * @param columnType    列类型
     * @return
     */
    public static String getDbType(String columnType) {
        if (StringUtil.indexOf(columnType, "(") > 0) {
            return StringUtil.substringBefore(columnType, "(");
        } else {
            return columnType;
        }
    }

    /**
     * 获取字段长度
     * 
     * @param columnType
     * @return
     */
    public static Integer getColumnLength(String columnType) {
        if (StringUtil.indexOf(columnType, "(") > 0) {
            String length = StringUtil.substringBetween(columnType, "(", ")");
            return Integer.valueOf(length);
        } else {
            return 0;
        }
    }

}